package com.gujianjian.testjwt.inteceptor;

import com.gujianjian.testjwt.aspect.PassToken;
import com.gujianjian.testjwt.dto.AccountDTO;
import com.gujianjian.testjwt.exceptions.NeedToLogin;
import com.gujianjian.testjwt.exceptions.UserNotExist;
import com.gujianjian.testjwt.service.AccountService;
import com.gujianjian.testjwt.utils.JwtUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 顾小健
 * @create: 2021-12-12
 */
public class JwtAuthInterceptor implements HandlerInterceptor {
    @Autowired
    AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //默认全部检查
        else {
            // 执行认证
            if (token == null) {
                //这里其实是登录失效,没token了   这个错误也是我自定义的，读者需要自己修改
                throw new NeedToLogin();
            }
            // 获取 token 中的 userId
            String userId = JwtUtils.getAudience(token);

            // 判断是否存在这个用户
            AccountDTO user = accountService.getByUserName(userId);
            if (user == null) {
                // 没有则抛出异常
                throw new UserNotExist();
            }

            // 验证 token ，如果验证失败则抛出异常，则请求失败
            JwtUtils.verifyToken(token, userId);
                
            //获取载荷内容
        	String userName = JwtUtils.getClaimByName(token, "username").asString();
        	String realName = JwtUtils.getClaimByName(token, "realname").asString();
        	
            //放入attribute以便后面调用
            httpServletRequest.setAttribute("username", userName);
            httpServletRequest.setAttribute("realname", realName);
            

            return true;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
